import { ref, h, watch } from 'vue';
import { ElInput, ElForm, ElFormItem } from 'element-plus';
import { useCodeName } from './useCodeName';
import { useMessageBox } from './useMessageBox';
import Code from '#/components/common/code.vue';
import { getVoiceVerificationCodeApi } from "#/api/core/auth"
import { getVerificationCodeApi } from '#/api';
import { $t } from '@vben/locales';

export interface CodeBoxOptions {
  title?: string;
  message?: string | any;
  adminName?: string;
  adminPhone?: string;
  confirmButtonText?: string;
  cancelButtonText?: string;
  callback?: (done: any) => void;
}

export const useCodeBox = () => {
  const authCode = ref('');
  const codeRef = ref();
  const { codeBtnName, isVoiceCode, codeInputPlaceholder } = useCodeName();
  const { confirm } = useMessageBox();

  const getCode = (adminPhone: string, fn: Function) => {
    console.log('getCode', isVoiceCode.value, codeBtnName.value);
    fn();
    if (isVoiceCode.value) {
      getVoiceVerificationCodeApi({ phoneNumber: adminPhone });
    } else {
      getVerificationCodeApi({ phoneNumber: adminPhone });
    }
  };

  const changeCodeType = (isVoice: boolean = false) => {
    if (codeRef.value.isCounting) return;
    console.log('changeCodeType', isVoice, codeRef.value.isCounting);
    isVoiceCode.value = isVoice;
    authCode.value = '';
  };

  const showCodeBox = (options: CodeBoxOptions = {}) => {
    const {
      title = $t('code.codeVerification'),
      message = $t('code.pleaseInputCode'),
      adminName = '',
      adminPhone = '',
      confirmButtonText = $t('code.confirmBtn'),
      cancelButtonText = $t('code.returnBtn'),
      callback = () => { }
    } = options;

    authCode.value = '';
    isVoiceCode.value = false;

    // 响应式 Code 组件
    const ReactiveCode = {
      setup() {
        return () => h(Code, {
          ref: codeRef,
          codeName: codeBtnName.value,
          authCode: adminPhone,
          onGetCode: (fn: Function) => getCode(adminPhone, fn)
        });
      }
    };

    // 响应式 el-form 校验
    const formRef = ref();
    const formData = ref({ authCode: '' });
    watch(authCode, val => { formData.value.authCode = val; });
    const formRules = {
      authCode: [
        { required: true, message: $t('code.codeRequired'), trigger: 'blur' },
        { min: 3, max: 10, message: $t('code.codeLengthError'), trigger: 'blur' }
      ]
    };
    const ReactiveForm = {
      setup() {
        return () => h(ElForm, {
          ref: formRef,
          model: formData.value,
          rules: formRules,
          labelWidth: '0px',
        }, {
          default: () => [
            h(ElFormItem, { prop: 'authCode' }, {
              default: () => h(ElInput, {
                modelValue: authCode.value,
                'onUpdate:modelValue': (value: string) => { authCode.value = value; },
                size: 'large',
                minlength: 3,
                maxlength: 10,
                placeholder: codeInputPlaceholder.value
              }, {
                append: () => h(ReactiveCode)
              })
            })
          ]
        });
      }
    };

    // 响应式提示
    const ReactiveMessage = {
      setup() {
        return () => h(
          'p',
          { class: "mt-2 text-right text-[#909399] text-xs" },
          isVoiceCode.value ? [
            '',
            h('a', {
              href: 'javascript:void(0)',
              class: 'text-blue-500 cursor-pointer ml-1',
              onClick: () => changeCodeType(false)
            }, $t('code.useSmsCode'))
          ] : [
            $t('code.noSmsReceived'),
            h('a', {
              href: 'javascript:void(0)',
              class: 'text-blue-500 cursor-pointer ml-1',
              onClick: () => changeCodeType(true)
            }, $t('code.voiceCode'))
          ]
        );
      }
    };

    // 自定义消息内容
    const customMessage = h('div', {}, [
      h('div', {}, message || ``),
      h('br'),
      h(ReactiveForm),
      h(ReactiveMessage)
    ]);
    // 校验表单
    confirm(customMessage, {
      confirmButtonText,
      cancelButtonText,
      dangerouslyUseHTMLString: true,
      beforeClose: (action: string, instance: any, done: () => void) => {
        if (action === 'confirm') {
          formRef.value.validate((valid: boolean) => {
            if (valid) {
              callback(done);
            }
          });
        } else {
          done();
        }
      }
    })
  };

  return {
    authCode,
    codeBtnName,
    isVoiceCode,
    codeInputPlaceholder,
    showCodeBox,
    getCode,
    changeCodeType
  };
};
